/**
 * copyright 2013 zy All rights reserved
 */


function initHighChartsTheme() {
	/**
	 * Grid theme for Highcharts JS
	 * @author Torstein Hønsi
	 */

	Highcharts.setOptions( {
		global : {
			useUTC : false
		}
	});

	Highcharts.theme = {
		colors : [ '#058DC7', '#50B432', '#ED561B', '#DDDF00', '#24CBE5',
				'#64E572', '#FF9655', '#FFF263', '#6AF9C4' ],
		chart : {
			width : '719',
			height: '500',
			backgroundColor : {
				linearGradient : {
					x1 : 0,
					y1 : 0,
					x2 : 1,
					y2 : 1
				},
				stops : [ [ 0, 'rgb(255, 255, 255)' ],
						[ 1, 'rgb(240, 240, 255)' ] ]
			},
			borderWidth : 2,
			plotBackgroundColor : 'rgba(255, 255, 255, .9)',
			plotShadow : true,
			plotBorderWidth : 1
		},
		title : {
			style : {
				color : '#000',
				font : 'bold 16px "Trebuchet MS", Verdana, sans-serif'
			}
		},
		subtitle : {
			style : {
				color : '#666666',
				font : 'bold 12px "Trebuchet MS", Verdana, sans-serif'
			}
		},
//		xAxis : {
//			gridLineWidth : 1,
//			lineColor : '#000',
//			tickColor : '#000',
//			labels : {
//				style : {
//					color : '#000',
//					font : '11px Trebuchet MS, Verdana, sans-serif'
//				}
//			},
//			title : {
//				style : {
//					color : '#333',
//					fontWeight : 'bold',
//					fontSize : '12px',
//					fontFamily : 'Trebuchet MS, Verdana, sans-serif'
//
//				}
//			}
//		},
//		yAxis : {
//			minorTickInterval : 'auto',
//			lineColor : '#000',
//			lineWidth : 1,
//			tickWidth : 1,
//			tickColor : '#000',
//			labels : {
//				style : {
//					color : '#000',
//					font : '11px Trebuchet MS, Verdana, sans-serif'
//				}
//			},
//			title : {
//				style : {
//					color : '#333',
//					fontWeight : 'bold',
//					fontSize : '12px',
//					fontFamily : 'Trebuchet MS, Verdana, sans-serif'
//				}
//			}
//		},

		tooltip : {
			valueDecimals : 8
		},
		
		lang : {  
	        months : ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'],  
	        weekdays : ['星期天', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六']  
	    },

//		xAxis: {
//            type: 'datetime',
//            dateTimeLabelFormats: { // don't display the dummy year
//                 month: '%Y-%m-%d',
//                 year: ''}
//       },

		legend : {
			itemStyle : {
				font : '9pt Trebuchet MS, Verdana, sans-serif',
				color : 'black'

			},
			itemHoverStyle : {
				color : '#039'
			},
			itemHiddenStyle : {
				color : 'gray'
			}
		},
		labels : {
			style : {
				color : '#99b'
			}
		},

		navigation : {
			buttonOptions : {
				theme : {
					stroke : '#CCCCCC'
				}
			}
		}
	};

	// Apply the theme
	var highchartsOptions = Highcharts.setOptions(Highcharts.theme);
}

function updateTablePrice( nRow, aData, iDisplayIndex, iDisplayIndexFull ) {
	var basePrice = getBasePrice();
	$('td:eq(0)', nRow).html((aData[0] * basePrice).toFixed(8));
	$('td:eq(2)', nRow).html((aData[2] * basePrice).toFixed(8));
}

function parseDate(strings){
    var _ = strings.split(' ');
    var ymd = _[0];
    var hms = _[1];

    var str = ymd.split('-');
    var fix = hms.split(':');

    var year  = str[0] - 0; 
    var month = str[1] - 0 - 1; 
    var day   = str[2] - 0; 
    var hour   = fix[0] - 0; 
    var minute = fix[1] - 0; 
    var second = fix[2] - 0;

    time = (new Date(year, month, day, hour, minute, second)).getTime();
    return time;
}

function updateHistoryTable( nRow, aData, iDisplayIndex, iDisplayIndexFull ) {
	if ( aData[1] == "Buy" ) {
		$('td:eq(1)', nRow).html( '<span style="color:green">买入</span>' );
	} else if ( aData[1] == "Sell" ) {
		$('td:eq(1)', nRow).html( '<span style="color:red">卖出</span>' );
 	}
	var basePrice = getBasePrice();
	$('td:eq(4)', nRow).html((aData[4] * basePrice).toFixed(8));
	$('td:eq(2)', nRow).html((aData[2] * basePrice).toFixed(8));
	$('td:eq(0)', nRow).html(new Date(parseDate(aData[0]) + 13 * 3600 * 1000).Format("yyyy-MM-dd hh:mm:ss"));
}

$.fn.dataTableExt.oApi.fnReloadAjax = function ( oSettings, sNewSource, fnCallback, bStandingRedraw ) {
    if ( sNewSource !== undefined && sNewSource !== null ) {
        oSettings.sAjaxSource = sNewSource;
    }
 
    // Server-side processing should just call fnDraw
    if ( oSettings.oFeatures.bServerSide ) {
        this.fnDraw();
        return;
    }
 
    this.oApi._fnProcessingDisplay( oSettings, true );
    var that = this;
    var iStart = oSettings._iDisplayStart;
    var aData = [];
 
    this.oApi._fnServerParams( oSettings, aData );
 
    oSettings.fnServerData.call( oSettings.oInstance, oSettings.sAjaxSource, aData, function(json) {
        /* Clear the old information from the table */
        that.oApi._fnClearTable( oSettings );
 
        /* Got the data - add it to the table */
        var aData =  (oSettings.sAjaxDataProp !== "") ?
            that.oApi._fnGetObjectDataFn( oSettings.sAjaxDataProp )( json ) : json;
 
        for ( var i=0 ; i<aData.length ; i++ )
        {
            that.oApi._fnAddData( oSettings, aData[i] );
        }
         
        oSettings.aiDisplay = oSettings.aiDisplayMaster.slice();
 
        that.fnDraw();
 
        if ( bStandingRedraw === true )
        {
            oSettings._iDisplayStart = iStart;
            that.oApi._fnCalculateEnd( oSettings );
            that.fnDraw( false );
        }
 
        that.oApi._fnProcessingDisplay( oSettings, false );
 
        /* Callback user function - for event handlers etc */
        if ( typeof fnCallback == 'function' && fnCallback !== null )
        {
            fnCallback( oSettings );
        }
    }, oSettings );
};

function initTables(marketId) {
	$.fn.dataTableExt.sErrMode = "throw";
	
	dtsellorderlist = $('#sellorderlist').dataTable({
						"bProcessing" : true,
						"sAjaxSource" : 'sell/'+ marketId + ".do",
						"sScrollY" : "300px",
						"bPaginate" : false,
						"bScrollCollapse" : true,
						"bFilter" : false,
						"bSort" : false,
						"bInfo" : false,
						"bAutoWidth" : true,
						"bProcessing" : false,
						"bDeferRender" : true,
						"fnRowCallback" : updateTablePrice,
						"oLanguage" : {
							"sEmptyTable" : "暂时没有卖单"
						}
					});

	dtbuyorderlist = $('#buyorderlist').dataTable({
						"bProcessing" : true,
						"sAjaxSource" : 'buy/'+ marketId + ".do",
						"sScrollY" : "300px",
						"bPaginate" : false,
						"bScrollCollapse" : true,
						"bFilter" : false,
						"bSort" : false,
						"bInfo" : false,
						"bAutoWidth" : true,
						"bProcessing" : false,
						"bDeferRender" : true,
						"fnRowCallback" : updateTablePrice,
						"oLanguage" : {
							"sEmptyTable" : "暂时没有买单"
						}
					});

	dttradehistory = $('#tradehistory').dataTable({
						"bProcessing" : true,
						"sAjaxSource" : 'his/'+ marketId + ".do",
						"sScrollY" : "300px",
						"bPaginate" : false,
						"bScrollCollapse" : true,
						"bFilter" : false,
						"bSort" : false,
						"bInfo" : false,
						"bAutoWidth" : false,
						"bProcessing" : false,
						"bDeferRender" : true,
						"fnRowCallback" : updateHistoryTable,
						"oLanguage" : {
							"sEmptyTable" : "暂时没有交易历史"
						}
					});

	// Reloading Market Tables

	function _reloaddatatables() {
		dtsellorderlist.fnReloadAjax();
		dtbuyorderlist.fnReloadAjax();
		dttradehistory.fnReloadAjax();
	}

	window.tablesInterval = setInterval(function() {
		_reloaddatatables();
	}, 10 * 30 * 1000);

}

function getBasePrice() {
	try {
		var price = $("#basePriceInput").val();
		price = parseFloat(price)
		if (isNaN(price)) {
			return defaultBasePrice;
		}
		return price;
	} catch (e) {
		return defaultBasePrice;
	}
}

function initStockChart(marketId, basePrice) {
	$.getJSON('chart/'+ marketId + ".do", function(data) {
		// split the data set into ohlc and volume
		var price = [], volume = [], dataLength = data.length;
		var basePrice = getBasePrice();
		
		for (i = 0; i < dataLength; i++) {
			var date = data[i][0];// + 1000 * 3600 * 13;
			var open = data[i][1] * basePrice;
			var high = data[i][2] * basePrice;
			var low = data[i][3] * basePrice;
			var close = data[i][4] * basePrice;
			price.push( [ date, // the date
					open, // open
					high, // high
					low, // low
					close // close
					]);
	
			volume.push( [ data[i][0], // the date
					data[i][5] // the volume
					])
		}
	
		// set the allowed units for data grouping
		var groupingUnits = [ [ 'minute', [ 5, 10, 15, 30 ] ],
				[ 'hour', [ 1, 2, 3, 4, 6, 8, 12 ] ],
				[ 'day', [ 1 ] ], [ 'week', [ 1 ] ],
				[ 'month', [ 1, 3, 6 ] ], [ 'year', null ] ];
	
		// create the chart
		$('#tradechart').highcharts('StockChart', {
			chart : {
				events : {
					load : function() {
						// set up the updating of the chart each second
						window.chartInterval = setInterval(function() {

							$.getJSON('chart'+ marketId + '.do', function(data) {
								// split the data set into ohlc and volume
								var price = [], volume = [], dataLength = data.length;

								for (i = 0; i < dataLength; i++) {
									var open = data[i][1] * basePrice;
									var high = data[i][2] * basePrice;
									var low = data[i][3] * basePrice;
									var close = data[i][4] * basePrice;
									var date = data[i][0];// + 1000 * 3600 * 13;
									price.push( [ 
											date, // the date
											open, // open
											high, // high
											low, // low
											close // close
										]);
									volume.push( [
													data[i][0], // the date
													data[i][5] // the volume
											])
								}

								var thischart = $('#tradechart').highcharts();
								thischart.series[0].setData(price);
								thischart.series[1].setData(volume);
							});
						}, 300 * 1000); // set interval end
					}
				}
			},
			tooltip: {
				dateTimeLabelFormats: {
					day: '%Y',
	                week: '%Y',
	                month: '%Y',
	                year: '%Y'
				}
			},
			rangeSelector : {
				buttons : [ {
					type : 'hour',
					count : 6,
					text : '6h'
				}, {
					type : 'day',
					count : 1,
					text : '1D'
				}, {
					type : 'week',
					count : 1,
					text : '1W'
				}, {
					type : 'month',
					count : 1,
					text : '1M'
				}, {
					type : 'all',
					count : 1,
					text : 'All'
				} ],
				selected : 1,
				inputEnabled : false
			},

//			title : {
//				text : 'CryptoBuck (BUK) 价格'
//			},
			credits : {
				enabled : false
			},
			yAxis : [ {
				title : {
					text : '价格'
				},
				height : 200,
				lineWidth : 2
			}, {
				title : {
					text : '交易量'
				},
				top : 300,
				height : 100,
				offset : 0,
				lineWidth : 2
			} ],

			series : [ {
				type : 'candlestick',
				id : 'pricedata',
				name : '人民币（CNY）',
				data : price,
				dataGrouping : {
					units : groupingUnits
				}
			}, {
				type : 'column',
				id : 'volumedata',
				name : 'Volume',
				data : volume,
				yAxis : 1,
				dataGrouping : {
					units : groupingUnits
				}
			} ]
//		  xAxis: { type: 'datetime' },
//          legend: { enabled: false },		 
//		  scrollbar:{enabled: false},
//		  navigator:{enabled: false}
		}); // end highcharts
	});
}

function load(marketid) {
	var price = $("#basePriceInput").val();
	price = parseFloat(price)
	if (isNaN(price)) {
		alert("自定义BTC/LTC价格失败，请重新输入");
		$("#basePriceInput").focus();
		return;
	}
	if (price == defaultBasePrice) {
		return;
	}
	var chart = $('#tradechart').highcharts();
	if (chart) {
		chart.destroy();
	}
	clearInterval(window.chartInterval);
	initStockChart(marketid);
	var sell = $('#sellorderlist').dataTable();
	if (sell) {
		sell.fnDestroy()
	}
	var buy = $('#buyorderlist').dataTable();
	if (buy) {
		buy.fnDestroy();
	}
	var his = $('#tradehistory').dataTable();
	if (his) {
		his.fnDestroy();
	}
	clearInterval(window.tablesInterval);
	initTables(marketid);
	
}

Date.prototype.Format = function(fmt) { //author: meizz 
    var o = {
        "M+": this.getMonth() + 1, //月份 
        "d+": this.getDate(), //日 
        "h+": this.getHours(), //小时 
        "m+": this.getMinutes(), //分 
        "s+": this.getSeconds(), //秒 
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度 
        "S": this.getMilliseconds() //毫秒 
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
    if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}

function searchLabel(keyword) {
	keyword = keyword.toUpperCase();
	$(".leftmarketinfo").each(function(i) {
		var $this = $(this);
		var label = $this.text().split("\n")[1];
		if (label.indexOf(keyword) >= 0) {
			$this.parent().show();
		} else {
			$this.parent().hide();
		}
	});
}
